$(document).ready(function(){
	var currentPage = 0;
	var pageSize = 10;
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");
	//获取用户状态下拉框
	var queryUserStateFun = function(){
		var url = adminQueryUrl + dicsService;
		console.log('url='+url+",toke="+token+",userId="+userId);
		var param = 'action=queryDicsList';
		param += "&dicsCode=USER_STATE";
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token:'"+token+"'");
				xhr.setRequestHeader("userId:'"+userId+"'");
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(result){
				if (result!=null && result.length>0){
					for (var i=0;i<result.length;i++){
						$("#queryUserState").append("<option value='"+result[i].keyValue+"'>"+result[i].keyName+"</option>");	
					}
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	};
	queryUserStateFun();
	//用于分页查询
	var queryPageListFun = function(){
		var url = adminQueryUrl + adminUserService;
		console.log('url2='+url+",toke="+token+",userId="+userId);
		var param = 'action=queryListPage';//请求到列表页面
		if ($("#queryUserName").val()!=''){
			param += "&queryUserName="+$("#queryUserName").val()
		}
		if ($("#queryUserState").val()!='' && $("#queryUserState").val()!=null){
			param += "&queryUserState="+$("#queryUserState").val()
		}
		if (currentPage>0){
			param += "&currentPage="+(currentPage-1);
		}
		param += "&pageSize="+pageSize;
		param += "&excludeUserId="+userId;
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token:'"+token+"'");
				xhr.setRequestHeader("userId:'"+userId+"'");
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data2='+data);
				$('#listDataGrid').empty();
				$('#listDataGrid').data('zui.datagrid',null);
				$('#listPager').empty();
				$('#listPager').data('zui.pager',null);
				if (data.success == '1'){
					if (data.pageTotal > 0){
						$('#listDataGrid').datagrid({
							checkable:true,
					        checkByClickRow: true,
						    dataSource: {
						        cols:[
						        	{name: 'userId', label: '1', width: 1},
						            {name: 'userName', label: '用户名', width: 134},
						            {name: 'trueName', label: '姓名', width: 109},
						            {name: 'userStateName', label: '用户状态', width: 109},
						            {name: 'mobile', label: '手机号码', width: 109},
						            {name: 'oprDate', label: '操作时间', width: -1}//-1用于自适应宽度
						        ],
						        cache:false,
						        array:data.pageList
						    }
						});
						//获取分页
						$('#listPager').pager({
						    page: data.currentPage,
						    recTotal: data.pageTotal,
						    recPerPage:pageSize,
						    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],
						    pageSizeOptions:[10,20,30,50,100]
						});
					}
					else {
						$("#listDataGrid").html("<center>查无数据</center>");
					}
				}
				else {
					$("#listDataGrid").html("查无数据");
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	};
	queryPageListFun();
	//监听分页，修改当前页，条数
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		console.log('currentPage='+currentPage+",pageSize="+pageSize);
		queryPageListFun();
	});
	//搜索
	$("#searchBtn").click(function(){
		queryPageListFun();
	});
	var tempFile ;//用于清除刚上传的文件
	//初始化添加
	$("#addBtn").click(function(){
		$("#addForm")[0].reset();
		if (tempFile!=null){
			$('#uploadHeadpic').data('zui.uploader').removeFile(tempFile);
			tempFile = null;
		}
		var url = adminQueryUrl + dicsService;
		var param = 'action=queryDicsList';
		param += "&dicsCodes='SEX','HOBBY'";
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token:'"+token+"'");
				xhr.setRequestHeader("userId:'"+userId+"'");
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				if (data!=null && data.length>0){
					var sexHtml = '';
					var hobbyHtml = '';
					$.each(data, function(i, item){   
						if(item.dicsCode == 'SEX'){
							sexHtml += "<label class='radio-inline'><input type='radio'  name='addSex' value='"+item.keyValue+"' >"+item.keyName+"</label>";
						}
						else if(item.dicsCode == 'HOBBY'){
							hobbyHtml += "<label class='checkbox-inline'><input type='checkbox' name='addHobby' value='"+item.keyValue+"'  >"+item.keyName+"</label>";
						}
					});  
					$("#sexDivId").html(sexHtml);
					$("#hobbyDivId").html(hobbyHtml);
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	$('#uploadHeadpic').uploader({
	    autoUpload: true,            // 当选择文件后立即自动进行上传操作
	    url: adminQueryUrl + fileService + "?action=uploadUserHeadpic",  // 文件上传提交地址
	    limitFilesCount:1,
	    responseHandler: function(responseObject, file) {
	    	addTempFile = file;
	    	if (responseObject!=null && responseObject.response!=null){
	    		var resultJson = JSON.parse(responseObject.response);
	    		if (resultJson.success!=null && resultJson.success!=''
		    			&& typeof(resultJson.success)!='undefined'
	    				&& resultJson.fileName!=''
		    			&& typeof(resultJson.fileName)!='undefined'){
	    			if (resultJson.success=='1' ){
	    				$("#addHeadpic").val(resultJson.fileName);
	    			}
	    		}
	    	}
	    }
	});
	//添加保存
	$("#addSave").click(function(){
		$("#addForm").validate({
			rules:{
				addUserName:{
					"required":true
				},
				addTrueName:{
					"required":true
				},
				addMobile:{
					"required":true
				},
				addPasswd:{
					"required":true
				},
				addSex:{
					"required":true
				},
				addHobby:{
					"required":true
				}
			},
			errorPlacement:function(error,element){
				error.appendTo(element.parent().parent());
			},
			submitHandler:function(form){
				if($("#addHeadpic").val()==''){
					new $.zui.Messager('请上传大头像!', {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
					return;
				}
				var hobbyValue = '';
				$("input[name='addHobby']:checked").each(function(item){
					hobbyValue += $(this).val()+",";
				});
				hobbyValue = hobbyValue.substr(0,hobbyValue.length-1);
				$("#addHobbyValue").val(hobbyValue);
				console.log('hobbyValue='+hobbyValue);
				$.ajax({
					url:adminQueryUrl + adminUserService,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token:'"+token+"'");
						xhr.setRequestHeader("userId:'"+userId+"'");
					},
					headers:{'token':token,'userId':userId},
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('添加成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	$('#addModal').modal('hide', 'fit');
		                	queryPageListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	//初始化修改
	$("#updateBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			if (tempFile!=null && $('#updateUploadHeadpicDiv')!=null){
				$('#updateUploadHeadpicDiv').data('zui.uploader').removeFile(tempFile);
				tempFile = null;
			}
			$("#updateForm")[0].reset();
			$("#uploadHeadpicDiv").css("display","none");
			$("#updateImgChangeBtn").css("display","none");
			$("#updateUploadHeadpicDiv2").css("display","none");
			$("#updateUploadHeadpicDiv").css("display","none");
			var url = adminQueryUrl + adminUserService;
			var param = 'action=initUpdate&updateUserId='+selectedItems[0].userId;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token:'"+token+"'");
					xhr.setRequestHeader("userId:'"+userId+"'");
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#updateModal').modal('show', 'fit');
						var sexHtml = '';
						var hobbyHtml = '';
						$.each(data.sexList, function(i, item){   
							if (item.keyValue==data.userMap.sex){
								sexHtml += "<label class='radio-inline'><input type='radio'  name='updateSex' value='"+item.keyValue+"' checked='checked' >"+item.keyName+"</label>";
							}
							else {
								sexHtml += "<label class='radio-inline'><input type='radio'  name='updateSex' value='"+item.keyValue+"' >"+item.keyName+"</label>";
							}
						});  
						$.each(data.hobbyList, function(i, item){ 
							var hobbyValue = data.userMap.hobby;
							if (hobbyValue!=null && hobbyValue!='' && typeof(hobbyValue)!='undefined'){
								var tempArray = hobbyValue.split(",");
								var checkFlag = '0';
								for(var i=0;i<tempArray.length;i++){
									if (item.keyValue==tempArray[i]){
										hobbyHtml += "<label class='checkbox-inline'><input type='checkbox' name='updateHobby' value='"+item.keyValue+"' checked='checked'  >"+item.keyName+"</label>";
										checkFlag = '1';
										break;
									}
								}
								if (checkFlag == '0'){
									hobbyHtml += "<label class='checkbox-inline'><input type='checkbox' name='updateHobby' value='"+item.keyValue+"'  >"+item.keyName+"</label>";
								}
							}
							else{
								hobbyHtml += "<label class='checkbox-inline'><input type='checkbox' name='updateHobby' value='"+item.keyValue+"'  >"+item.keyName+"</label>";
							}
						});
						$("#updateSexDivId").html(sexHtml);
						$("#updateHobbyDivId").html(hobbyHtml);
						$("#updateUserId").val(data.userMap.userId);
						$("#updateUserName").val(data.userMap.userName);
						$("#updateTrueName").val(data.userMap.trueName);
						$("#updateMobile").val(data.userMap.mobile);
						$("#updatePasswd").val(data.userMap.passwd);
						var headpic = data.userMap.headpic;
						if (headpic!=null && headpic!='' && typeof(headpic)!='undefined'){
							var imgSrc = adminQueryUrl + "/" + headpic;
							var imgHtml = '<a href="'+imgSrc+'" target="_blank"><img src="'+imgSrc+'" width="200px" height="200px" class="img-thumbnail" alt="缩略图"></a>';
							$("#uploadHeadpicDiv").css("display","block");
							$("#uploadHeadpicDiv").html(imgHtml);
							$("#updateHeadpic").val(data.userMap.headpic);
							$("#updateImgChangeBtn").css("display","block");
						}
						else{
							$("#uploadHeadpicDiv").css("display","none");
							$("#updateImgChangeBtn").css("display","none");
							$("#updateUploadHeadpicDiv2").css("display","block");
							$("#updateUploadHeadpicDiv").css("display","block");
						}
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	//监听修改页面的文件上传
	$('#updateUploadHeadpicDiv').uploader({
	    autoUpload: true,            // 当选择文件后立即自动进行上传操作
	    url: adminQueryUrl + fileService + "?action=uploadUserHeadpic",  // 文件上传提交地址
	    limitFilesCount:1,
	    responseHandler: function(responseObject, file) {
	    	tempFile = file;
	    	if (responseObject!=null && responseObject.response!=null){
	    		var resultJson = JSON.parse(responseObject.response);
	    		if (resultJson.success!=null && resultJson.success!=''
		    			&& typeof(resultJson.success)!='undefined'
	    				&& resultJson.fileName!=''
		    			&& typeof(resultJson.fileName)!='undefined'){
	    			if (resultJson.success=='1' ){
	    				$("#updateHeadpic").val(resultJson.fileName);
	    			}
	    		}
	    	}
	    }
	});
	//修改保存
	$("#updateSave").click(function(){
		var validAreaCodeUrl = adminQueryUrl + areaService + "?action=validAreaCode";
		var validAreaNameUrl = adminQueryUrl + areaService + "?action=validAreaName";
		$("#updateForm").validate({
			rules:{
				updateTrueName:{
					"required":true
				},
				updateMobile:{
					"required":true
				},
				updateSex:{
					"required":true
				},
				updateHobby:{
					"required":true
				}
			},
			errorPlacement:function(error,element){
				error.appendTo(element.parent().parent());
			},
			submitHandler:function(form){
				if($("#updateHeadpic").val()==''){
					new $.zui.Messager('请上传大头像!', {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
					return;
				}
				var hobbyValue = '';
				$("input[name='updateHobby']:checked").each(function(item){
					hobbyValue += $(this).val()+",";
				});
				hobbyValue = hobbyValue.substr(0,hobbyValue.length-1);
				$("#updateHobbyValue").val(hobbyValue);
				console.log('hobbyValue='+hobbyValue);
				
				$.ajax({
					url:adminQueryUrl + adminUserService+"?action=update",
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token:'"+token+"'");
						xhr.setRequestHeader("userId:'"+userId+"'");
					},
					headers:{'token':token,'userId':userId},
					data:$(form).serialize(),
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('修改成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryPageListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	//显示删除确认框
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var areaDataGrid = $('#areaDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = areaDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#deleteModal').modal('show', 'fit');
		}
	});
	//删除地区
	$("#deleteAreaBtn").click(function(){
		// 获取数据表格实例
		var areaDataGrid = $('#areaDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = areaDataGrid.getCheckItems();
		var url = adminQueryUrl + areaService;
		var param = 'action=delete&areaCode='+selectedItems[0].areaCode;//请求到列表页面
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token:'"+token+"'");
				xhr.setRequestHeader("userId:'"+userId+"'");
			},
			headers:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#deleteModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryAreaListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	//初始化详情
	$("#detailBtn").click(function(){
		// 获取数据表格实例
		var areaDataGrid = $('#areaDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = areaDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + areaService;
			var param = 'action=detail&areaId='+selectedItems[0].areaId;//请求到列表页面
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token:'"+token+"'");
					xhr.setRequestHeader("userId:'"+userId+"'");
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('data='+data);
					if (data.success=='1'){
						$('#detailModal').modal('show', 'fit');
						$("#detailAreaCode").html(data.areaMap.areaCode);
						$("#detailAreaName").html(data.areaMap.areaName);
						$("#detailAreaParentCode").html(data.areaMap.areaParentName);
						$("#detailSortNo").html(data.areaMap.sortNo);
						$("#detailOprId").html(data.areaMap.trueName);
						$("#detailOprDate").html(data.areaMap.oprDate);
						$("#detailDescription").html(data.areaMap.description);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
});
//变更图片
function updateImgChange(){
	$("#uploadHeadpicDiv").css("display","none");
	$("#updateImgChangeBtn").css("display","none");
	$("#updateUploadHeadpicDiv").css("display","block");
	$("#updateUploadHeadpicDiv2").css("display","block");
	//$('#updateUploadHeadpicDiv').data('zui.uploader').destroy();
}